var priceSpans;
var product;

var noneSelectImgSrc = "";
var selectImgSrc = "";
var shopCar;

// var selacted = "";
// var noneSlacted = "";
function generateOrder(){
    var p = shopCar[0];
    var product = {
        title: p.title,
        price: p.view_price,
        count: "1",
        pic: p.pic_url,
        nid: p.nid

    };
    var  order_form = [];
    for(var i= 0;i <shopCar.length;i++){
        product = shopCar[i];
        order_form.push(product);
    }
    console.log(shopCar);

    localStorage.setItem("order_form", JSON.stringify(order_form));

    location.href = "order_form_page.html";
}



window.onload = function() {
    // 显示loading
    $.showPreloader();
    $("#shopCarDiv").hide();
    var loadedImageCount = 0;

//如果购物车里没有商品，价格结算就消失，购物车空空如也图片显示
    shopCar = JSON.parse(localStorage.getItem("shopCar"));
    if (!shopCar||shopCar.length==0) {
        emptyCar.style.display = "block";
        total_box.style.display = "none";
        $.hidePreloader();
    } else {
        shopCarCount.innerHTML = "购物车("+ shopCar.length+")";//购物车如果有商品，标题会显示购物车中有几件商品
        for (var i = 0; i < shopCar.length; i++) {
            product = shopCar[i];
            var productDiv = document.createElement("div");
            productDiv.className = "product";


            var selectImg = document.createElement("img");//创建一个图片标签，图片地址是未选中状态的图片
            selectImg.src = noneSelectImgSrc;
            selectImg.style.height = "20px";
            selectImg.className = "ckimg";
            selectImg.onclick = function(){                 //点击图片事件，如果图片是未选中状态，就切换到选中状态图片
 //                 this.src = this.src == selectImgSrc
 //                   ?noneSelectImgSrc:selectImgSrc;

                if(this.src == selectImgSrc){
                    this.src = noneSelectImgSrc;
                }else{
                    this.src = selectImgSrc;
                }
            };

            var productImage = document.createElement("img");
            productImage.src = "http:"+product.pic;
            productImage.style.height = "100px";
            productImage.onload = function(){
                loadedImageCount++;
                if(loadedImageCount==shopCar.length){
                    $.hidePreloader();
                    $("#shopCarDiv").show(300);
                }
            };

            var productInfoDiv = document.createElement("div");

            var titleDiv = document.createElement("div");
            titleDiv.className = "titleDiv";
            titleDiv.innerHTML = product.title;

            var priceAndCountDiv = document.createElement("div");
            priceAndCountDiv.className = "priceAndCountDiv";

            var priceSpan = document.createElement("span");
            priceSpan.innerHTML = "&yen; " + (product.price*product.count).toFixed(2);
            priceSpan.pr = product.price;
            priceSpan.className="priceSpan";
            priceSpan.style.color = "#eb6029";
            priceSpan.style.fontSize = "16px";

            //var countSpan = document.createElement("span");
            //countSpan.className="countSpan";
            // countSpan.innerHTML = "x " + product.count;
            priceAndCountDiv.appendChild(priceSpan);
            //priceAndCountDiv.appendChild(countSpan);
            productInfoDiv.appendChild(titleDiv);
            productInfoDiv.appendChild(priceAndCountDiv);

            var minusDiv = document.createElement("span");
            minusDiv.className = 'minus_Div';
            minusDiv.innerHTML = "-";
            productInfoDiv.appendChild(minusDiv);

            //var promptMessage = document.createElement("div");
            //promptMessage.className = "promptMessage";
            //promptMessage.innerHTML = "受不了啦！不能再减啦！";


            var numDiv = document.createElement("span");
            numDiv.className = 'num_Div';
            numDiv.innerHTML = product.count;
            numDiv.pc=product.count;
            productInfoDiv.appendChild(numDiv);

            var addDiv = document.createElement("span");
            addDiv.className = 'add_Div';
            addDiv.innerHTML = "+";
            productInfoDiv.appendChild(addDiv);


            var deleteBtn = document.createElement("img");
            deleteBtn.src = "images/删除.png";
            deleteBtn.style.width = "0.8rem";
            deleteBtn.style.float = "right";
            deleteBtn.type = "button";
            productInfoDiv.appendChild(deleteBtn);
            deleteBtn.nid = product.nid;
            deleteBtn.onclick = function(){
                deleteProductFromShopCart(this,this.nid);
                totalPrice();
            };

            //productDiv.appendChild(promptMessage);
            productDiv.appendChild(selectImg);
            productDiv.appendChild(productImage);
            productDiv.appendChild(productInfoDiv);
            shopCarDiv.appendChild(productDiv);

        }
    }
    var minus = document.getElementsByClassName("minus_Div");
    var nums = document.getElementsByClassName("num_Div");
    var adds = document.getElementsByClassName("add_Div");
    //var countSpans = document.getElementsByClassName("countSpan");
    var priceSpans = document.getElementsByClassName("priceSpan");

    for(var i=0; i < minus.length; i++){
        minus[i].index = i;
        minus[i].onclick = function () {
            var p = this.index;
            if(parseFloat(nums[p].innerHTML) == 1){
                //promptMessage.style.display = "block";
                this.style.color = "#ccc";
                $.toast("受不了啦！不能再减啦！");

                return;
            }
            nums[p].innerHTML = parseInt(nums[p].innerHTML) - 1;
            //priceSpans[p].innerHTML = (nums[p].innerHTML*parseFloat(priceSpans[p].pr)).toFixed(2);
            totalPrice();
        };
    }

    for (var j=0; j < adds.length; j++) {
        adds[j].index = j;
        adds[j].onclick = function () {
            var p = this.index;
            nums[p].innerHTML = parseInt(nums[p].innerHTML) + 1;
            //priceSpans[p].innerHTML = (nums[p].innerHTML*parseFloat(priceSpans[p].pr)).toFixed(2);
            totalPrice();
        };
    }
    totalPrice();

    allSelectImg.onclick = function(){

        console.log(this);

        this.src = this.src == selectImgSrc?
            noneSelectImgSrc:selectImgSrc;
        allSelectImg.className = "ckselect";
        var allSelectImgSrc = this.src;

        // jquery 中循环函数 each
        // 这个函数有两个参数，
        // index 表示循环索引
        // ele 表示循环的元素（标签）
        // .ckimg 就是每个商品前面选择图片
        $(".ckimg").each(function(index,ele){
            totalPrice();
            ele.src = allSelectImgSrc;
            totalPrice();
        });
        totalPrice();
    };


    singleChkImg();
};



function singleChkImg() {
    var aChkImg = document.getElementsByClassName("ckimg");
    console.log(aChkImg);

    for (var i = 0; i < aChkImg.length; i++) {
        aChkImg[i].onclick = function () {
            this.src = this.src == selectImgSrc ? noneSelectImgSrc:selectImgSrc;
            totalPrice();
        }
    }

}


function totalPrice() {
    var q = document.getElementsByClassName("ckimg");
    var pris = document.getElementsByClassName("priceSpan");
    var nums = document.getElementsByClassName("num_Div");
    var totalCount = 0;
    for(var i = 0;i<q.length;i++){
        if(q[i].src==selectImgSrc){
            var o = parseFloat(pris[i].pr)*parseInt(nums[i].innerHTML);
            totalCount += o;
        }
    }
    total_prices.innerHTML=totalCount.toFixed(2);
}





function deleteProductFromShopCart(deleteBtn,nid){
    var totalprice = document.getElementById('total_prices');

    for(var i=0;i<shopCar.length;i++){
        // 如果购物车对象中已经存在了这个商品
        if(shopCar[i].nid == nid){
            console.log(shopCar[i]);
            console.log(shopCar[i].price);
            var subTotal = parseFloat(shopCar[i].price) * parseInt(shopCar[i].count);
            console.log(subTotal);
            $.confirm('您确定要移除该宝贝吗?', function () {
                shopCar.splice(i,1);
                console.log(i);
                $(deleteBtn).parents(".product").css("height",
                    $(deleteBtn).parents(".product").height());
                setTimeout(function(){
                    $(deleteBtn).parents(".product").css("opacity",0);
                    $(deleteBtn).parents(".product").css("height",0);
                    $(deleteBtn).parents(".product").remove();
                },1);
                shopCarCount.innerHTML = "购物车("+ shopCar.length+")";
                $.toast("移除成功！");
                if(shopCar.length==0){
                    emptyCart.style.display = "block";
                    total_box.style.display = "none";
                }
                var total = parseFloat(totalprice.innerHTML);
                console.log(total);
                total = total - parseFloat(subTotal);
                totalprice.innerHTML=total.toFixed(2);

                // 存进本地存储，替换原来的购物车信息
                localStorage.setItem("shopCar",JSON.stringify(shopCar));
            });

            break;
        }
    }




}
